/*
 * Copyright 2011 yura.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.opu.db_vdumper.util.datacopy;

import java.sql.Connection;
import org.opu.db_vdumper.util.StringUtil;

/**
 *  
 * @author yura
 */
public class DataMoverUtility {

    /**
     * Static method to process a database type. Sometimes database
     * types are not reported exactly as they need to be for proper
     * syntax. This method corrects the database type and size.
     * @param type The type reported
     * @param i The size of this column
     * @return The properly formatted type, for this database
     */
    public static String processType(String type, int size, Connection connection) {
//        String usigned = "UNSIGNED";
//        int i = type.indexOf(usigned);
//        if (i != -1) {
//            type = type.substring(0, i) + type.substring(i + usigned.length());
//        }

        if (type.equalsIgnoreCase("varchar") && (size == 65535)) {
            type = "TEXT";
        }

        return type.trim();
    }

    public static String createQuery(String query, Object... args) {
        for (int i = 0; i < args.length; i++) {
            if (args[i].toString().indexOf('\'') != -1){
                args[i] = args[i].toString().replaceAll("'", "\\'");
            }
        }

        return String.format(query.replaceAll("\\?", "\'%s\'"), args);
    }



    public static String tableStr(String table, String schema){
        StringBuilder sb = new StringBuilder();

        sb.append('"');

        if (StringUtil.ifStr(schema)){
            sb.append(schema).append("\".\"");
        }

        sb.append(table).append('"');

        return sb.toString();
    }

    public static String fieldNameStr(String name){
        return "\"" + name + "\"";
    }

    public static String fieldValueStr(String value){
        return "'" + value + "'";
    }
}
